﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using WatiN.Core;

namespace AxialWeb.Tests
{
	[TestFixture]
	public class TestPageTests : IDisposable
	{
		private Process p;

		[TestFixtureSetUp]
		public void SetUp()
		{
			// create a new process to start the ASP.Net Development Server
			p = new Process();
			string path = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName + @"\";
			p.StartInfo.FileName = "WebDev.WebServer.EXE";
			p.StartInfo.WorkingDirectory = @"C:\Program Files\Common Files\Microsoft Shared\DevServer\9.0\";
			p.StartInfo.Arguments = String.Format("/port:2877 /path:\"{0}AxialWeb\"", path);
			p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
			p.Start();
		}

		[TestFixtureTearDown]
		public void Dispose()
		{
			// kill the ASP.NET Development Server process
			p.Kill();
		}

		public static Regex EndsWith(string id)
		{
			return new Regex(".*" + id + "$");
		}

		[Test]
		public void JSWindow()
		{
			using (IE ie = new IE("http://localhost:2877/JSWindow.aspx"))
			{
				Assert.AreEqual("Window Object", ie.Title);

				var counter = ie.Span("lblIntervalIn1").InnerHtml;
				Assert.AreNotEqual("", ie.Image("blankimg").Src);
				Assert.AreNotEqual("", ie.Link("goesnowhere").Url);
				Assert.IsNull(ie.Span(EndsWith("lblTimeoutIn2")).InnerHtml);

				Thread.Sleep(2000);
				Assert.AreNotEqual(counter, ie.Span("lblIntervalIn1").InnerHtml);
				Assert.IsNotNull(ie.Span(EndsWith("lblTimeoutIn2")).InnerHtml);
			}
		}

		[Test]
		public void Form()
		{
			using (IE ie = new IE("http://localhost:2877/Form.aspx"))
			{
				Assert.AreEqual("Simple Form", ie.Title);

				Assert.IsNull(ie.Span(EndsWith("lblNameError")).InnerHtml);
				Assert.IsNull(ie.Span(EndsWith("lblColorError")).InnerHtml);
				ie.Button(EndsWith("btnSave")).Click();
				Assert.IsNotNull(ie.Span(EndsWith("lblNameError")).InnerHtml);
				Assert.IsNotNull(ie.Span(EndsWith("lblColorError")).InnerHtml);

				ie.TextField(EndsWith("txtName")).Value = "dan goldstein";
				ie.TextField(EndsWith("txtColor")).Value = "blue";
				ie.Button(EndsWith("btnSave")).Click();
				Assert.IsNull(ie.Span(EndsWith("lblNameError")).InnerHtml);
				Assert.IsNull(ie.Span(EndsWith("lblColorError")).InnerHtml);

				Assert.AreEqual("10", ie.SelectList(EndsWith("ddlLevel2")).Options[0].Text);
				ie.SelectList(EndsWith("ddlLevel1")).Select("2");
				Assert.AreNotEqual("10", ie.SelectList(EndsWith("ddlLevel2")).Options[0].Text);
			}
		}
	}
}
